package com.cn.service;

import com.cn.dao.MenuDao;
import com.cn.dao.RoleDao;
import com.cn.dao.UserDao;
import com.cn.domain.UserDetail;
import com.cn.utils.JwtUtils;
import com.cn.vo.UserAndTokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * Created by chenyuncong on 2019/9/16.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private MenuDao menuDao;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public UserAndTokenVo login(String account, String password) {
        //authenticate()方法会触发UserDetailsService.loadUserByUsername()方法，CustomUserDetailsService继承UserDetailsService会触发里面的loadUserByUsername()方法
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(account, password));
        //存储认证信息
        SecurityContextHolder.getContext().setAuthentication(authentication);

        final UserDetail userDetail = (UserDetail) authentication.getPrincipal();
        final String token = jwtUtils.generateAccessToken(userDetail);
        jwtUtils.putToken(account,token);
        return new UserAndTokenVo(token,userDetail);
    }

    @Override
    public void logout(String token) {

    }

    @Override
    public UserAndTokenVo refresh(String oldToken) {
        return null;
    }

    @Override
    public UserDetail getUserByToken(String token) {
        return null;
    }
}
